import React, { useState, useEffect, useMemo } from 'react';
import { Drawer, Button, Form, Input, Tree } from 'antd';

export default function TreeDrawer(props) {
  const { setTheRole, theRole, modiRoleAsync } = props;
  console.log('theRole', theRole);
  const [treeForm] = Form.useForm();
  const formAndSend = async () => {
    const formData = treeForm.getFieldsValue();
    const { roleId, menuId } = theRole;
    await modiRoleAsync({ roleId, ...formData, menuId: menuId.join(',') });
  };
  const drawerFooter = (
    <Button onClick={formAndSend} type="primary">
      修改
    </Button>
  );
  const treeCheck = (checkedKeys) => {
    setTheRole({ ...theRole, menuId: checkedKeys });
  };
  const showr = (a) => {
    console.log('a', a);
    return a;
  };
  let drawerInfo = useMemo(() => {
    if (theRole) {
      if (theRole.drawerType == 'view') {
        return { ...drawerInfo, canModify: false, title: '角色信息' };
      } else if (theRole.drawerType == 'modify') {
        return { ...drawerInfo, canModify: true, title: '修改角色' };
      } else {
        return {};
      }
    } else {
      return {};
    }
  }, [theRole]);

  return (
    <>
      <Drawer
        destroyOnClose="true"
        footer={drawerFooter}
        width={650}
        title={drawerInfo.title}
        placement="right"
        onClose={() => {
          setTheRole(null);
          treeForm.resetFields();
        }}
        visible={theRole}
      >
        {theRole ? (
          <>
            {theRole.roleName}
            <Form form={treeForm} initialValues={showr(theRole)}>
              <Form.Item label="角色名称" name="roleName">
                <Input disabled={!drawerInfo.canModify}></Input>
              </Form.Item>
              <Form.Item label="角色描述" name="remark">
                <Input.TextArea
                  disabled={!drawerInfo.canModify}
                ></Input.TextArea>
              </Form.Item>
            </Form>
            <Tree
              checkedKeys={theRole.menuId}
              onCheck={treeCheck}
              treeData={props.allMenus}
              multiple
              checkable
              disabled={!drawerInfo.canModify}
              defaultExpandAll={!drawerInfo.canModify}
            ></Tree>
          </>
        ) : null}
      </Drawer>
    </>
  );
}
